package com.lebang.configuration;

import com.lebang.service.log.LogService;
import com.lebangweb.response.Callback;
import com.lebangweb.response.JsonData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Set;

/**
 * controller 全局异常处理
 *
 * @author hwq
 * @since 2019/11/11
 */
@Slf4j
@ControllerAdvice
public class MyControllerAdvice {
    @Autowired
    private LogService logService;

    /**
     * 全局异常捕捉处理
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public JsonData errorHandler(Exception ex) {
        logService.addLog(ex);
        return Callback.fail("800", "网络异常", ex);
    }

    /**
     * 全局异常捕捉处理
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    public JsonData errorHandler(HttpRequestMethodNotSupportedException ex) {
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attr.getRequest();
        String uri = request.getRequestURI();
        log.error("请求接口不存在:" + uri);
        return Callback.fail("800", "接口不存在", ex);
    }

}
